What is an Interface?
An interface in Java is a blueprint of a class. It is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class.
Declaration of an Interface
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Here is the syntax to declare an interface:
Interface declaration syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Example of an Interface in Java Here’s an example of an interface in Java:
Basic example of an Interface in Java - how to use interface
// Interface declaration
interface Printable {
void print();
}
// Class that implements the interface
class Main implements Printable {
public void print() {
System.out.println("Hello");
}
public static void main(String args[]) {
Main obj = new Main();
obj.print();
}
}
Output
Hello
In this example, Printable is an interface that has a method print(). The class A6 implements Printable and provides the implementation for the print() method.
Why Use Java Interface?
There are mainly three reasons to use interface:
✦ It is used to achieve abstraction.
✦ By interface, we can support the functionality of multiple inheritance.
✦ It can be used to achieve loose coupling.
✦ Java 8 Interface Improvement Since Java 8, an interface can have default and static methods. Moreover, it adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default, and the methods are public and abstract.
Remember, an interface in Java is a collection of methods. You can use it to define a set of behaviors that a class should implement. A class can implement multiple interfaces, and all the methods defined in an interface must be implemented by any class that implements it.